package cn.edu.lingnan.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component

public class AliOSSUtils {
    String endpoint="oss-cn-beijing.aliyuncs.com" ;

    String accessKeyId="LTAI5tDzs9vuTg6wGaJyNkbw" ;
    String accessKeySecret="hXTP0L2WolyrH9sZwIdSOEKaHA06Uv";
    String bucketName="ongoingife";


    /**
     * 普通上传
     */
    public String upload(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = "https://ongoingife.oss-cn-beijing.aliyuncs.com/"+ fileName;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

    /**
     * 实现上传图片到OSS，并覆盖旧文件
     */
    public String uploadReplace(MultipartFile file, Integer projectId) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 生成固定文件名，包含文件后缀
        String fileName = "ProjectImg_" + projectId + "." + getFileExtension(file.getOriginalFilename());

        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除旧文件（如果存在）
        ossClient.deleteObject(bucketName, fileName);

        // 上传新文件
        ossClient.putObject(bucketName, fileName, inputStream);

        // 文件访问路径
        String url = "https://ongoingife.oss-cn-beijing.aliyuncs.com/" + fileName;

        // 关闭 ossClient
        ossClient.shutdown();
        return url; // 把上传到oss的路径返回
    }

    /**
     * 获取文件后缀名
     */
    private String getFileExtension(String filename) {
        if (filename == null) {
            return "";
        }
        int lastIndexOfDot = filename.lastIndexOf('.');
        if (lastIndexOfDot == -1) {
            return "";
        }
        return filename.substring(lastIndexOfDot + 1);
    }

    public void delete(String imgUrl) {
        // 解析图片路径
        String[] split = imgUrl.split("/");
        String fileName = split[split.length - 1];

        // 删除文件
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, fileName);

        // 关闭 ossClient
        ossClient.shutdown();
    }
}
